<template>
  <view>
    <view class="search-box-container">
      <uni-search-bar :radius="100" cancelButton="none"  @input="input"></uni-search-bar>
    </view>
    <!-- 搜索建议 -->
    <!-- 根据搜索结果是否为空展示搜索历史或搜索建议 -->
    <view class="sugg-list" v-if="searchResult.length !== 0">
      <!-- 给每一项绑定点击事件，跳转到商品详情页面 -->
      <view class="sugg-item" v-for="(item ,i) in searchResult" :key="i" @click="goToDetail(item.goods_id)">
        <view class="goods-name">
          {{item.goods_name}}
        </view>
        <uni-icons type="forward" size="16"></uni-icons>
      </view>
    </view>
    <!-- 搜索历史 -->
    <view class="search-history" v-else>
       <!-- 标题区域 -->
       <view class="hisyory-title">
         <view class="search-title">
           搜索历史
         </view>
         <uni-icons type="trash-filled" size="16" @click="clean"></uni-icons>
       </view>
     
      <!-- 列表区域 -->
      <view class="search-list">
        <uni-tag :text="item" v-for="(item , i ) in histories" :key="i" @click="goToGoodsList(item)"></uni-tag>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        timer: null,
        keyWord: '',
        // 搜索建议列表
        searchResult: [],
        // 搜索历史
        historyList: []
      };
    },
    onLoad() {
      //页面加载时获取存储中的数据
      this.historyList =JSON.parse(uni.getStorageSync('kw') || '[]') 
    },
    methods: {
      input(e) {
        //setTimeout 处理输入框防抖
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.keyWord = e.value
          //根据输入的关键词发请求搜索联想建议
          this.getSearchResult()

          // console.log(this.keyWord);
          // console.log(res);
        }, 500)
      },
      async getSearchResult() {
        //keywords 为空时
        if (this.keyWord.length === 0) {
          this.searchResult = []
          return
        }
        const res = await uni.$http.get('/goods/qsearch', {
          query: this.keyWord
        })
        if (res.data.meta.status !== 200) {
          uni.showMsg('获取数据失败', 1500)
        }
        this.searchResult = res.data.message
        this.addSerchHistory(this.keyWord)
        console.log(res.data);
      },
      // 跳转到商品详情页面
      goToDetail(goods_id) {
        console.log('ok');
        uni.navigateTo({
          url: '/subpkg/goods-detail/goods-detail?goods_id='+ goods_id
        })
      },
      // 添加搜索历史关键词
      addSerchHistory(kw){
        // this.historyList.push(kw)
        // 利用set方法对数组去重
        const set = new Set(this.historyList)
        //删除数组中与当前输入关键词重复的元素
        set.delete(this.keyWord)
        //再添加当前关键词
        set.add(this.keyWord)
        //再将当前set对象转化为数组重新赋值给historyList
        this.historyList = Array.from(set)
        //将搜索记录持久化
        uni.setStorageSync('kw',JSON.stringify(this.historyList))
        console.log(set);
      },
      clean(){
        this.historyList = []
        uni.getStorageSync('kw' , '[]')
      },
      goToGoodsList(kw){
        uni.navigateTo({
          url:'/subpkg/goods-list/goods-list?query=' + kw
        })
      }
    },
    computed:{
      //设置计算属性监听搜索历史变化，将数组翻转，让最新搜索历史排在最前面，
      histories(){
        return [...this.historyList].reverse()
      }
    }
  }
</script>

<style lang="scss">
  .search-box-container {
    position: sticky;
    top: 0;
    z-index: 999;
  }

  .sugg-list {
    padding: 0 5px;

    .sugg-item {
      display: flex;
      font-size: 12px;
      border-bottom: 1px solid #efefef;
      padding: 13px 0;
      align-items: center;
      justify-content: space-between;

      .goods-name {
        white-space: nowrap; //不允许换行
        overflow: hidden; //隐藏超出部分
        text-overflow: ellipsis; //文本超出部分用 ... 代替
        margin-right: 3px;
      }
    }
  }
  .hisyory-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    font-size: 13px;
    border-bottom: 1px solid #efefef;
  }
  .search-list  {
    display: flex;
    flex-wrap: wrap;
    uni-tag {
      margin-top: 5px;
      margin-left: 5px;
    }
  }
</style>
